﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using StockMonitor.Business;
using StockMonitor.Configuration;
using CarolLib.Control;
using CarolLib;

namespace StockMonitor
{
    public partial class frmMain : Form
    {
        Dictionary<Guid, MdiUserControl> Mdis;
        MenuStrip menuMain;

        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            this.Mdis = ModuleHelper.LoadALLModules();
            menuMain = ModuleHelper.CreateModuleMenu(Mdis.Values.ToList(), subMenu_Click);
            menuMain.Font = this.Font;
            this.Controls.Add(menuMain);

            MdiUserControl defaultModule = ModulesConfiguration.GetConfig().DefaultModule;

            if (defaultModule != null && Mdis.Values.Where(f => f.ModuleID == defaultModule.ModuleID).Count() > 0)
            {
                this.mdiTabCantainer1.AddMdiForm(defaultModule);
            }
        }

        void subMenu_Click(object sender, EventArgs e)
        {
            Guid id = (Guid)(sender as ToolStripMenuItem).Tag;
            this.mdiTabCantainer1.AddMdiForm(Mdis[id]);
        }

        private void frmMain_FormClosed(object sender, FormClosedEventArgs e)
        {
        }

        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            //{
            //    ThreadPool.QueueUserWorkItem(o =>
            //    {
            try
            {
                TradeContext.Instance.TodayEntrusts.UpdateStatus();
            }
            catch (StockMonitor.Helper.HsGateway.HsCommException hsex)
            {
                Log.Exception("交易接口返回错误", hsex);
            }
            catch (Exception ex)
            {
                Log.Exception("系统错误", ex);
            }
            //});

            if (e.CloseReason == CloseReason.UserClosing)
            {
                if (DialogResult.OK == MessageBox.Show("您确定要退出程序吗？", "退出确认", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation))
                {
                    Log.Info("退出系统");
                    Application.Exit();
                }
                else
                {
                    e.Cancel = true;
                }
            }
        }
    }
}
